package com.cryptape.cita_wallet.service;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;

import com.alm.token.MyApp;
import com.cryptape.cita_wallet.activity.SplashActivity;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * Date： 2018/10/28
 * Description:
 *
 * @author WangLizhi
 * @version 1.0
 */

public class LanguageKeeper {

    public static final String LANGUAGE_EN = "en";
    public static final String LANGUAGE_CN = "CN";

    public static final String LANGUAGE_JA = "ja";
    public static final String LANGUAGE_KO = "ko";

    public static final String LANGUAGE_SAVE = "LANGUAGE";
    public static final String LANGUAGE_TYPE = "LANGUAGE_TYPE";
    public static final String ACTION_CHANGE_LOACL_LANGUAGE = "multiLanguageChanged";

//    private  SharedPreferences mSaveSp;
    private static LanguageKeeper INSTANCE = null;

    public static LanguageKeeper getInstance(){
        if(INSTANCE == null){
            INSTANCE = new LanguageKeeper();
        }
        return INSTANCE;
    }

    private LanguageKeeper(){
//        mSaveSp = MyApp.getsInstance()()().getSharedPreferences(LANGUAGE_SAVE, Context.MODE_PRIVATE);
    }

    public  String getLanguage(Context context){
        SharedPreferences sp = context.getSharedPreferences(LANGUAGE_SAVE, Context.MODE_PRIVATE);
       return sp.getString(LANGUAGE_TYPE, LANGUAGE_EN);
    }

    public void setLanguage(String language){
        SharedPreferences sp = MyApp.getsInstance().getSharedPreferences(LANGUAGE_SAVE, Context.MODE_PRIVATE);
        Log.e("MainActivity","setLanguage"+"type:"+language);
        sp.edit().putString(LANGUAGE_TYPE, language).commit();
    }

    /**
     * 设置App默认语言
     * @param type
     */
    public void setLoaclLanguage(Context context,String type){
        setLanguage(type);
        changeLocale(context,type);
        Intent intent = new Intent(context, SplashActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);

//        sendLanguageChoiceBroadcast();
    }

    private void sendLanguageChoiceBroadcast(){
        Intent localIntent = new Intent(ACTION_CHANGE_LOACL_LANGUAGE);
        MyApp.getsInstance().sendBroadcast(localIntent);
    }

//    public void initLocalLanguage(){
//        String type = getLanguage();
//        Log.e("MainActivity","initLocalLanguage"+"type:"+type);
//        changeLocale(type);
//    }


    /**
     * 设置app语言类型
     * @param type 语言类型
     */
    private void changeLocale(Context context,String type) {
        Log.e("MaiActivity","changeLocale:"+type);

        switch (type) {
            case LANGUAGE_CN:
            default:
                switchLanguage(context,Locale.SIMPLIFIED_CHINESE);
                break;
            case LANGUAGE_EN:
                switchLanguage(context,Locale.ENGLISH);
                break;
            case LANGUAGE_JA:
                switchLanguage(context,Locale.JAPAN);
                break;
            case LANGUAGE_KO:
                switchLanguage(context,Locale.KOREA);
                break;
        }

    }

    /**
     * 修改本地语言设置
     * @param locale
     */
    private void switchLanguage(Context context,Locale locale) {
        Resources resources = context.getResources();// 获得res资源对象
        Configuration config = resources.getConfiguration();// 获得设置对象
        DisplayMetrics dm = resources.getDisplayMetrics();// 获得屏幕参数：主要是分辨率，像素等。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            config.setLocale(locale);
        }else{
            config.locale = locale; // 本地语言设置
        }
        resources.updateConfiguration(config, dm);
    }

    public   Context attachBaseContext(Context context) {
//        LanguageKeeper keeper = new LanguageKeeper(this);
        String language = getLanguage(context);
        Log.e("MainActivity","attachBaseContext language:"+language);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //安卓7.0以上
            return createConfigurationResources(context, language);
        } else {
            //
            applyLanguage(context, language);
            return context;
        }
    }

    public void init(Context context) {
        // 1.从「系统」或者「APP缓存」拿到语言对象
         String language = getLanguage(context);
         Locale locale = getSupportLanguage(language);
        // 1.1.提交语言到APP缓存
        // 2.从Activity方更新语言配置
        updateConfiguration(context, locale.getLanguage(), locale.getCountry());
        // 3.从Application方更新语言配置
        if (context instanceof Activity) {
            updateConfiguration(context.getApplicationContext(), locale.getLanguage(), locale.getCountry());
        }
    }

    /**
     * (核心) 更新语言配置
     *
     * @param context 上下文
     * @param lang    需要切换的语言
     * @param cn      地区
     */
    @SuppressLint("ObsoleteSdkInt")
    private static void updateConfiguration(Context context, String lang, String cn) {
        // 1.创建语言对象--> 如果不提供国家码则按照母系语种切换
        Locale locale;
        // 1.1.统一国家码大写
        if (TextUtils.isEmpty(cn)) {
            locale = new Locale(lang);
        } else {
            locale = new Locale(lang, cn.toUpperCase());
        }
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();

//        Build.VERSION_CODES.N
        // 2.根据版本进行参数设置
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(locale);
        } else {
            configuration.locale = locale;
        }
        DisplayMetrics dm = resources.getDisplayMetrics();
        resources.updateConfiguration(configuration, dm);
    }

    public static void applyLanguage(Context context, String newLanguage) {
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        Locale locale = getSupportLanguage(newLanguage);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // apply locale
            configuration.setLocale(locale);
        } else {
            // updateConfiguration
            ////安卓7.0以下
            configuration.locale = locale;
        }
        DisplayMetrics dm = resources.getDisplayMetrics();
        resources.updateConfiguration(configuration, dm);
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context createConfigurationResources(Context context, String language) {
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        Locale locale;
        if (TextUtils.isEmpty(language)) {//如果没有指定语言使用系统首选语言
            locale = getSystemPreferredLanguage();
        } else {//指定了语言使用指定语言，没有则使用首选语言
            locale = getSupportLanguage(language);
        }
        configuration.setLocale(locale);
        return context.createConfigurationContext(configuration);
    }

    private static Map<String, Locale> mSupportLanguages = new HashMap<String, Locale>(7) {{
        put(LANGUAGE_EN, Locale.ENGLISH);
        put(LANGUAGE_CN, Locale.SIMPLIFIED_CHINESE);
        put(LANGUAGE_KO, Locale.KOREA);
        put(LANGUAGE_JA, Locale.JAPAN);
    }};

    /**
     * 是否支持此语言
     *
     * @param language language
     * @return true:支持 false:不支持
     */
    public static boolean isSupportLanguage(String language) {
        return mSupportLanguages.containsKey(language);
    }

    @TargetApi(Build.VERSION_CODES.N)
    public static Locale getSupportLanguage(String language) {
        if (isSupportLanguage(language)) {
            return mSupportLanguages.get(language);
        }
        return getSystemPreferredLanguage();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public static Locale getSystemPreferredLanguage() {
        Locale locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            locale = LocaleList.getDefault().get(0);
        } else {
            locale = Locale.getDefault();
        }
        return locale;
    }
}
